﻿using System.ComponentModel;
using System.Globalization;

namespace Swimj.Core.Converter
{
    public class SimpleFuncConverter : TypeConverter
    {
        private readonly Type tIn;
        private readonly Type tOut;
        private Func<object?, object> converterFunc;
        private readonly bool allowAssignableInputs;

        public SimpleFuncConverter(Type tIn, Type tOut, Func<object?, object> converterFunc, bool allowAssignableInputs)
        {
            this.tIn = tIn;
            this.tOut = tOut;
            this.converterFunc = converterFunc;
            this.allowAssignableInputs = allowAssignableInputs;
        }

        public void SetConverterFunc(Func<object?, object> fn)
        {
            converterFunc = fn;
        }

        public override object ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value,
            Type destinationType)
        {
            return converterFunc(value);
        }

        public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
        {
            if (allowAssignableInputs)
            {
                return tIn.IsAssignableFrom(sourceType);
            }

            return sourceType == tIn;
        }

        public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType)
        {
            if (destinationType != null)
                return destinationType.IsAssignableFrom(tOut);
            return false;
        }
    }
}